package com.hula.onion.book.server.spider.platforms.yiminjinrong;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by work on 2018/1/20.
 */
@Component
public class YmjrSpiderHelper {

    public Map<String, Object> installRequestParams(LoginForm loginForm) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("userName", loginForm.getUserName());
        map.put("pwd", loginForm.getPassword());
        return map;
    }


    public boolean checkLogin(String html) {
        try {
            Document document = Jsoup.parse(html);
            Element el = document.selectFirst("p.password_wrong");
            if (el != null) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 解析账户余额
     *
     * @param accountStr
     * @return
     */
    public CommonResponse parseAccountBalance(String accountStr) {
        try {

            Document document = Jsoup.parse(accountStr);
            String amount = document.selectFirst("#total").text();
            String totalInterest = document.selectFirst("#sumInterest").text();
            String waitInterest = document.selectFirst("#interest").text();
            AccountInfo accountInfo = new AccountInfo();
            accountInfo.setAmount(new BigDecimal(amount));
            accountInfo.setWaitIntrest(new BigDecimal(waitInterest));
            accountInfo.setTotalIntrest(new BigDecimal(totalInterest));
            return new CommonResponse(accountInfo);

        } catch (Exception e) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
    }
}
